import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
import babel from '@babel/core';
import removeConsolePlugin from 'babel-plugin-transform-remove-console';

export default function jsonInjectorPlugin(options?: { path?: string }) {
	const jsonFilePath = path.resolve(options?.path || './vscodeconfig.json'); // 默认路径
	return {
		name: 'vite-plugin-json-injector',
		config(config:any,env:any) {
			let hastoClearLog = false;
			if (!fs.existsSync(jsonFilePath)) {
				console.error(`JSON file not found at: ${jsonFilePath}`);
				return {};
			}
            const jsonData = JSON.parse(fs.readFileSync(jsonFilePath, 'utf-8'));
            if(jsonData && jsonData.onlineProduct && jsonData.onlineProduct.enabled){
				const gitBranchInclude:Array<any> = jsonData.onlineProduct.gitBranchInclude || [];
				const currentGitBranch = execSync("git rev-parse --abbrev-ref HEAD").toString().trim();
				if(gitBranchInclude.includes(currentGitBranch) && env.mode === 'production'){
					hastoClearLog = true;
				}
			}
			// @ts-ignore
			globalThis.__CLEAR_LOG__ = hastoClearLog;
			return {
                define:{
                    __JSON_CONFIG__: jsonData,   
                }
            };
		},
		transform(code:string, id:string, options:object){
			// 只处理 JavaScript/TypeScript 文件
			if (!id.endsWith('.js') && !id.endsWith('.ts')) {
				return code;
			}
			// @ts-ignore
			if (globalThis.__CLEAR_LOG__ && process.env.NODE_ENV === 'production') {
				const result = babel.transformSync(code, {
					plugins: [
					  [removeConsolePlugin, { exclude: ['error', 'warn', 'info', 'debug'] }]  // 只移除 console.log
					],
					sourceMaps: false,  // 关闭 sourcemap 生成
					filename: id,       // 文件路径
				});
				return {
					code: result ? result.code : code,
					map: result ? result.map : null // sourcemap，这里可以传递为 `null` 或者 `undefined`
				};
			}
			return code;
		},
		// 添加热更新支持
		handleHotUpdate({ file, server }:{ file: string, server: any}) {
			if (file === jsonFilePath) {
				const jsonData = JSON.parse(fs.readFileSync(jsonFilePath, 'utf-8'));
				// 重新注入数据
				server.ws.send({
					type: 'custom',
					event: 'json-update',
					data: jsonData,
				});
				console.log('JSON file updated:', jsonData);
			}
		}
	}
}

